package com.homedo.microservice.open.service.gateway.manager.web.task;


import com.google.common.collect.Lists;
import com.homedo.common.util.Detect;
import com.homedo.microservice.open.service.gateway.manager.web.bean.po.ServiceGateway;
import com.homedo.microservice.open.service.gateway.manager.web.persistence.dao.ServiceGatewayDao;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.turbine.plugins.PluginsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.turbine.TurbineAggregatorProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 动态增加断路器监控
 */
@Component
public class TurbineConfUpdateTask {
    @Autowired
    private ServiceGatewayDao serviceGatewayDao;
    @Autowired
    private TurbineAggregatorProperties turbineAggregatorProperties;


    private static final Logger LOGGER = LoggerFactory.getLogger(TurbineConfUpdateTask.class);

    @Scheduled(cron = "0/6 * * * * ?")
    public void dbConfUpdateTask() {

        this.doSchedule();

    }

    private void doSchedule() {
        ConcurrentCompositeConfiguration myConfiguration =
                (ConcurrentCompositeConfiguration) DynamicPropertyFactory.getInstance().getBackingConfigurationSource();

        List<ServiceGateway> serviceGateways = serviceGatewayDao.getAll();

        if (Detect.notEmpty(serviceGateways)) {
            List<String> clusters = Lists.newArrayList();

            serviceGateways.forEach(e -> {
                if (Detect.notEmpty(e.getHystrixUrl())) {

                    String cluster = e.getName() + "_" + e.getEnv();
                    clusters.add(cluster);

                    myConfiguration.setOverrideProperty("turbine.instanceInsertPort." + cluster, "true");
                    myConfiguration.setOverrideProperty("turbine.ConfigPropertyBasedDiscovery." + cluster + ".instances", e.getHystrixUrl());
                    myConfiguration.setOverrideProperty("turbine.instanceUrlSuffix." + cluster, "/hystrix.stream");
                }
            });

            if (Detect.notEmpty(clusters)) {
                String clustersStr = "";
                for (int i = 0; i < clusters.size(); i++) {
                    if (i == clusters.size() - 1) {
                        clustersStr += clusters.get(i);
                    } else {
                        clustersStr += clusters.get(i) + ",";
                    }
                }

                myConfiguration.setOverrideProperty("turbine.aggregator.clusterConfig", clustersStr);

                turbineAggregatorProperties.setClusterConfig(clusters);
                PluginsFactory.getClusterMonitorFactory().initClusterMonitors();
            }
        }

    }

}
